package com.hd.platform.util;

import com.google.gson.reflect.TypeToken;
import com.hd.platform.util.exception.ServiceException;
import com.hd.platform.util.exception.DBExceptionEnums;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/**
 * 签名计算工具
 * @author xuzhen
 *
 */
public class SignUtil {
	private  static String key = ConfigUtil.getProperty("HTTP_SERVICE_KEY");

	public static void  checkRequestJson(Object req)
	{
		if(req==null) return;
		String reqjson= JsonUtil.toJson(req);
		Map<String, String> requestContent = null;
		requestContent = (Map<String, String>) JsonUtil.fromJson(reqjson, new TypeToken<Map<String, String>>() {
		}.getType());
		if(StringUtils.isEmpty(requestContent.get("issign"))||"0".equalsIgnoreCase(requestContent.get("issign")))
			return;
		String sign=requestContent.get("sign");
		String timestamp=requestContent.get("timestamp");
		if(StringUtils.isEmpty(sign))
			throw new ServiceException(DBExceptionEnums.SIGN_IS_NULL);
		if(StringUtils.isEmpty(timestamp))
			throw new ServiceException(DBExceptionEnums.TIMESTAMP_IS_NULL);
		if (!sign.equals(SignUtil.createSign(new TreeMap<String, String>(requestContent), key).toString()))
			throw new ServiceException(DBExceptionEnums.SIGNATURES_ERROR);

	}



	/**
	 * 创建md5摘要,规则是:按www参数名称a-z排序,遇到空值的参数不参加签名。
	 */
	public static String createSign(TreeMap parameters,String key) {
		StringBuffer sb = new StringBuffer();
		parameters.remove("sign");
		parameters.remove("key");
		parameters.remove("issign");
		parameters.remove("appversion");
		parameters.remove("uasystem");
		parameters.remove("operuid");
		parameters.remove("devicetype");
		parameters.remove("deviceid");
		parameters.remove("idfa");
		Set es = parameters.entrySet();
		Iterator it = es.iterator();
		String k ="";
		String v ="";

		while(it.hasNext()) {
			Map.Entry entry = (Map.Entry)it.next();
			k = (String)entry.getKey();
			v = (String)entry.getValue();
			if(null != v && !"".equals(v)) {
				sb.append(k + "=" + v + "&");
			}
		}
		sb.append("key=" + key);
		String sign = Md5Util.getInstance().getMD5String(sb.toString()).toUpperCase();
		return sign;	
	}

}
